package com.echronos.thirdsync.mq.AutoCount;

import com.alibaba.fastjson.JSONObject;
import com.echronos.rabbitmq.receiver.MqReceiver;
import com.echronos.thirdsync.constants.MqConstant;
import com.echronos.thirdsync.mq.AutoCount.message.AutoCountBaseMessage;
import com.echronos.thirdsync.mq.AutoCount.receiver.MessageDispatcher;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 消费者
 *
 * @Author wangyadong
 * @Date 2025/8/12 15:35
 * @ClassName AutoCountCommonReceiver
 */
@Slf4j
@Component
public class AutoCountCommonConsumer extends MqReceiver {
    @Resource
    private MessageDispatcher messageDispatcher;

    @Override
    //@RabbitListener(queues = MqConstant.QUEUE_AUTO_COUNT_PURCHASE_ORDER)
    public void onMessage(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 1. 反序列化消息体为CommonMessage
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        try {
            AutoCountBaseMessage<?> commonMessage = JSONObject.parseObject(body, AutoCountBaseMessage.class);
            // 2. 分发消息到业务处理器
            messageDispatcher.dispatch(commonMessage);
        } catch (Exception e) {
            // 异常处理：重试或拒绝（根据策略）
            log.error("消息接收异常：body={},exception={}", message.getBody(), e);
        } finally {
            // 3. 手动确认消息
            channel.basicAck(deliveryTag, true);
        }
    }
}
